import { App } from 'vue'
import Skeleton from './skeleton/index.vue'
import Carousel from './carousel/index.vue'
import More from './more/index.vue'
import Bread from './Bread/index.vue'
import BreadItem from './Bread/Item.vue'
import City from './city/index.vue'
import NumBox from './numbox/index.vue'
import Button from './button/index.vue'
import CheckBox from './checkbox/index.vue'
import Dialog from './dialog/index.vue'
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'

export default {
	install(app: App) {
		app.component(Skeleton.name, Skeleton)
		app.component(Carousel.name, Carousel)
		app.component(More.name, More)
		app.component('XtxBread', Bread)
		app.component('XtxBreadItem', BreadItem)
		app.component('XtxCity', City)
		app.component('XtxNumBox', NumBox)
		app.component('XtxButton', Button)
		app.component('XtxCheckBox', CheckBox)
		app.component('XtxDialog', Dialog)

		// 自定义指令
		app.directive('lazy', {
			mounted(dom: HTMLImageElement, binding) {
				const { stop } = useIntersectionObserver(dom, ([isIntersecting]) => {
					if (isIntersecting) {
						dom.src = binding.value
						// 停止监听
						stop()
						// 错误处理
						dom.onerror = () => {
							dom.src = defaultImg
						}
					}
				})
			},
			unmounted(dom: HTMLImageElement) {
				dom.onerror = null
			},
		})
	},
}
